<?php
/**
 * User: LuYuanXun
 * Date: 2018/09/14
 * Time: 16:00
 */

namespace App\Services\ThirdAPI;

use App\Models\Game;
use common\utils\RedisKeys;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use common\enum\CommonEnum;
use common\utils\SysCode;

class MWAPIService
{
    protected $apiName = 'MW';

    /**
     * 获取mw游戏名字列表
     * @return array
     * @throws \Exception
     */
    public function getGameNames()
    {
        $data = Game::where(['partner_name' => $this->apiName])->get()->toArray();
        $needUpdate = Redis::set(RedisKeys::MW_LOCK_GAMES, date("Y-m-d H:i:s"), 'nx', 'ex', 3600);
        if (!$data || $needUpdate) {
            $data = $this->getGameList();
        }

        $games = [];
        foreach ($data as $d) {
            $games[$d['game_code']] = $d['name'];
        }

        return $games;
    }

    /**
     * 获取游戏列表
     * @return array|mixed
     * @throws \Exception
     */
    public function getGameList()
    {
        $url = config('app.rpcserver') . "/api/getGameList";
        $ret = GameApiService::request($url, 'get', ['api_name' => $this->apiName]);
        $currentData = Game::where(['partner_name' => $this->apiName])->get()->toArray();
        $formatData = [];
        foreach ($currentData as $value) {
            $formatData[$value['game_code']] = $value;
        }
        $partnerInfo = GameApiService::getApiPartnerInfoByName($this->apiName);
        $insertData = [];
        foreach ($ret["games"] as $v) {
            if (!isset($formatData[$v['gameId']])) {
                $insertData[] = [
                    'partner_id' => $partnerInfo['id'],
                    'partner_name' => $partnerInfo['name'],
                    'name' => $v['gameName'],
                    'extend' => json_encode(['gameState' => $v['gameState'], 'gameStatus' => $v['gameStatus'], 'jackpotStatus' => $v['jackpotStatus']]),
                    'img_url' => $v['gameIcon'],
                    'game_code' => $v['gameId'],
                    'game_url' => "/game/third?g=mw&c=oauth&gameId={$v['gameId']}",
                    'game_type' => CommonEnum::GAME_EGAME, // 电子游戏
                ];
            }
        }

        if (count($insertData) > 0) {
            GameApiService::saveGame($insertData);
            if (!$ret) {
                Redis::del(RedisKeys::MW_LOCK_GAMES);
                return error_exit(SysCode::INTERNAL_SERVER_ERROR, "保存失败：" . json_encode($ret->getErrors(), JSON_UNESCAPED_UNICODE));
            }
        }

        return array_merge($formatData, $insertData);
    }

    /**
     * 代理商获取玩家游戏下注数据或总社获取玩家游戏下注日志   OK
     * @param $startTime
     * @param $endTime
     * @return mixed
     * @throws \Exception
     */
    public function getOrders($startTime, $endTime)
    {
        $url = config('app.rpcserver') . "/api/getOrders";
        return GameApiService::request($url, 'get', ['api_name' => $this->apiName, 'start_time' => $startTime, 'end_time' => $endTime]);
    }

    /**
     * 处理时间差
     * @param $timestamp
     * @return int
     */
    public function handleTime($timestamp = null)
    {
        $timestamp = $timestamp ?? time();
        return date('Y-m-d H:i:s', $timestamp - 43200);//美东时间与北京时间相差12h
    }
}